# -*- coding: utf-8 -*-
import sys

from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask import request
from utils.config import config
import time
import re

app = Flask(__name__)
app.secret_key = 'EskRU$*uxwtf9%PHD2@KtVESMWCd1UAuqknSC#cJ'
app.config['SQLALCHEMY_DATABASE_URI'] = config["SQLALCHEMY_DATABASE_URI"]
app.config['SQLALCHEMY_POOL_RECYCLE'] = 120
app.config['SQLALCHEMY_POOL_TIMEOUT'] = 20
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

reload(sys)
sys.setdefaultencoding('utf-8')


class Sms_config(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    sms_type = db.Column(db.Integer)
    sms_number = db.Column(db.String(255))
    sms_regex = db.Column(db.String(255))
    time_interval = db.Column(db.Integer)
    sms_desc = db.Column(db.String(50))

    def __init__(self, sms_type, sms_number, sms_regex, time_interval):
        self.sms_type = sms_type
        self.sms_number = sms_number
        self.time_interval = time_interval
        self.sms_regex = sms_regex

    def __repr__(self):
        return '<Sms_config %d: %s%s>' % (self.id, self.sms_number, self.sms_regex)

    def to_json(self):
        return {
            "id": self.id,
            "sms_type": self.sms_type,
            "sms_number": self.sms_number,
            "sms_regex": self.sms_regex,
            "time_interval": self.time_interval,
            "sms_desc": self.sms_desc,
        }


class Sms_info(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    sms_number = db.Column(db.String(20))
    sms_content = db.Column(db.String(255))
    sms_verify_code = db.Column(db.String(50))
    sms_type = db.Column(db.Integer)
    sms_time = db.Column(db.String(50))

    def __init__(self, sms_number, sms_content, sms_time):
        self.sms_number = sms_number
        self.sms_content = sms_content
        self.sms_time = sms_time

    def __repr__(self):
        return '<Sms_info %d: %s%s>' % (self.id, self.sms_number, self.sms_verify_code)

    def to_json(self):
        return {
            "id": self.id,
            "sms_number": self.sms_number,
            "sms_content": self.sms_content,
            "sms_verify_code": self.sms_verify_code,
            "sms_type": self.sms_type,
            "sms_time": self.sms_time,
        }


@app.route('/monkey')
def hello_world():
    return 'Hello World!'


@app.route('/monkey/get_config')
def get_config():
    sms_type_m = request.args.get('sms_type')
    query = Sms_config.query
    item = query.filter_by(sms_type=sms_type_m).first()
    return jsonify({'status': 0, 'msg': 'get config success', 'data': item.to_json()})


@app.route('/monkey/update_config', methods=['POST', 'GET'])
def update_config():
    sms_type_m = request.form['sms_type']
    query = Sms_config.query
    sms_config_item = query.filter_by(sms_type=sms_type_m).first()
    sms_config_item.sms_number = request.form['sms_number']
    sms_config_item.sms_regex = request.form['sms_regex']
    sms_config_item.time_interval = request.form['time_interval']
    db.session.commit()
    return jsonify({'status': 0, 'msg': 'update config success', 'data': ""})


@app.route('/monkey/add_sms_info', methods=['POST', 'GET'])
def add_sms_info():
    inset = Sms_info(sms_number=request.form['sms_number'],
                     sms_content=request.form['sms_content'],
                     sms_time=request.form['sms_time'])
    db.session.add(inset)
    db.session.commit()
    return jsonify({'status': 0, 'msg': 'add sms success', 'data': ""})


@app.route('/monkey/get_sms_info')
def get_sms_info():
    sms_type_m = request.args.get('sms_type')
    query = Sms_info.query
    sms_info_items = query.order_by(Sms_info.id.desc()).offset(0).limit(5)
    print sms_info_items
    if not sms_info_items:
        return jsonify({'status': 0, 'msg': 'no sms', 'data': ''})

    # 获取配置
    query_config = Sms_config.query
    config_item = query_config.filter_by(sms_type=sms_type_m).first()
    print config_item.to_json()

    status = -1
    for sms_info_item in sms_info_items:
        sms_time = float(sms_info_item.sms_time)
        current_time = float(str(time.time()))
        print "sms_time", sms_time
        print "current_time", current_time
        if current_time - sms_time < config_item.time_interval < 0:
            continue
        elif current_time - sms_time > config_item.time_interval * 60:
            continue

        # return jsonify({'status': 0, 'msg': '当前服务器时间小于短信时间，短信时间错误', 'data': ''})

        if config_item.sms_number in sms_info_item.sms_number \
                and config_item.sms_regex in sms_info_item.sms_content:
            # 正则提取验证码
            pat = "[0-9]{4,}"
            m = re.search(pat, sms_info_item.sms_content)
            if m:
                sms_info_item.sms_verify_code = m.group()
                status = 0
                return jsonify({'status': 0, 'msg': 'success', 'data': sms_info_item.to_json()})
                break
            else:
                status = 1
                continue
        else:
            status = 2
            continue

    if status == 1 or status == 2:
        return jsonify({'status': 0, 'msg': 'no sms verify code', 'data': ''})
    elif status == 0:
        pass
    else:
        return jsonify({'status': 0, 'msg': 'no sms', 'data': ''})


if __name__ == '__main__':
    # app.run()
    app.run(host='0.0.0.0', debug=True, threaded=True)
